<template>
  <div class="work-experience-step">
    <div class="step-header">
      <h3>工作经验</h3>
      <p>请填写您的工作经历，同一公司可以添加多个岗位</p>
    </div>

    <!-- 按公司分组显示 -->
    <div class="company-groups">
      <div
        v-for="(companyGroup, companyName) in groupedExperiences"
        :key="companyName"
        class="company-group"
      >
        <div class="company-header">
          <h4 class="company-name">{{ companyName }}</h4>
          <el-button
            type="text"
            size="small"
            @click="addPositionToCompany(companyName)"
          >
            <el-icon><Plus /></el-icon>
            添加岗位
          </el-button>
        </div>

        <div class="positions-list">
          <div
            v-for="(experience, index) in companyGroup"
            :key="experience.id || `${companyName}-${index}`"
            class="position-item"
          >
            <el-form
              :model="experience"
              :rules="rules"
              label-width="100px"
              class="experience-form"
            >
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="公司名称" prop="company_name">
                    <el-input
                      v-model="experience.company_name"
                      placeholder="请输入公司名称"
                      @input="handleCompanyNameChange(experience, $event)"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="岗位名称" prop="position_name">
                    <el-input v-model="experience.position_name" placeholder="请输入岗位名称" />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="开始时间" prop="start_date">
                    <el-date-picker
                      v-model="experience.start_date"
                      type="month"
                      placeholder="请选择开始时间"
                      style="width: 100%"
                      format="YYYY-MM"
                      value-format="YYYY-MM"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="结束时间" prop="end_date">
                    <el-date-picker
                      v-model="experience.end_date"
                      type="month"
                      placeholder="请选择结束时间"
                      style="width: 100%"
                      format="YYYY-MM"
                      value-format="YYYY-MM"
                      :disabled="experience.is_current"
                    />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-form-item>
                <el-checkbox v-model="experience.is_current">目前在职</el-checkbox>
              </el-form-item>

              <el-form-item label="岗位职责" prop="job_responsibilities">
                <el-input
                  v-model="experience.job_responsibilities"
                  type="textarea"
                  placeholder="请详细描述您在该岗位的主要职责和工作内容"
                  :rows="4"
                />
              </el-form-item>

              <el-form-item label="工作成果" prop="achievements">
                <el-input
                  v-model="experience.achievements"
                  type="textarea"
                  placeholder="请描述在该岗位取得的主要成果和业绩（选填）"
                  :rows="3"
                />
              </el-form-item>

              <div class="form-actions">
                <el-button
                  @click="removeExperience(experience)"
                  v-if="workExperienceList.length > 1"
                >
                  删除
                </el-button>
              </div>
            </el-form>
          </div>
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <div v-if="workExperienceList.length === 0" class="empty-state">
      <el-empty description="暂无工作经验">
        <el-button type="primary" @click="addExperience">
          添加第一份工作经验
        </el-button>
      </el-empty>
    </div>

    <div class="step-actions">
      <el-button @click="addExperience" v-if="workExperienceList.length > 0">
        <el-icon><Plus /></el-icon>
        添加工作经验
      </el-button>
      <el-button type="primary" @click="handleSave" :loading="saving">
        保存工作经验
      </el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage, type FormRules } from 'element-plus'
import { workExperienceApi, type WorkExperience } from '@/api/resume'

// Props
interface Props {
  resumeId: number
}

// Emits
interface Emits {
  (e: 'completed', completed: boolean): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 响应式数据
const loading = ref(false)
const saving = ref(false)
const workExperienceList = ref<WorkExperience[]>([])

// 表单验证规则
const rules: FormRules = {
  company_name: [
    { required: true, message: '请输入公司名称', trigger: 'blur' }
  ],
  position_name: [
    { required: true, message: '请输入岗位名称', trigger: 'blur' }
  ],
  start_date: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  job_responsibilities: [
    { required: true, message: '请输入岗位职责', trigger: 'blur' }
  ]
}

// 按公司分组的工作经验
const groupedExperiences = computed(() => {
  const groups: Record<string, WorkExperience[]> = {}

  workExperienceList.value.forEach(experience => {
    const companyName = experience.company_name || '未命名公司'
    if (!groups[companyName]) {
      groups[companyName] = []
    }
    groups[companyName].push(experience)
  })

  return groups
})

// 监听工作经验变化，判断是否完成
watch(workExperienceList, () => {
  checkCompletion()
}, { deep: true })

// 检查完成状态
const checkCompletion = () => {
  const hasValidExperience = workExperienceList.value.some(experience =>
    experience.company_name && experience.position_name &&
    experience.start_date && experience.job_responsibilities
  )
  emit('completed', hasValidExperience)
}

// 获取工作经验列表
const fetchWorkExperienceList = async () => {
  loading.value = true
  try {
    const response = await workExperienceApi.getWorkExperienceList(props.resumeId)
    const data = response.data || response

    if (data.results && data.results.length > 0) {
      workExperienceList.value = data.results
    } else if (Array.isArray(data) && data.length > 0) {
      workExperienceList.value = data
    } else {
      addExperience()
    }
  } catch (error) {
    addExperience()
  } finally {
    loading.value = false
  }
}

// 添加工作经验
const addExperience = () => {
  workExperienceList.value.push({
    company_name: '',
    position_name: '',
    start_date: '',
    end_date: '',
    is_current: false,
    job_responsibilities: '',
    achievements: '',
    order: workExperienceList.value.length
  })
}

// 为指定公司添加岗位
const addPositionToCompany = (companyName: string) => {
  workExperienceList.value.push({
    company_name: companyName,
    position_name: '',
    start_date: '',
    end_date: '',
    is_current: false,
    job_responsibilities: '',
    achievements: '',
    order: workExperienceList.value.length
  })
}

// 处理公司名称变化
const handleCompanyNameChange = (experience: WorkExperience, newCompanyName: string) => {
  experience.company_name = newCompanyName
}

// 删除工作经验
const removeExperience = async (experience: WorkExperience) => {
  if (experience.id) {
    try {
      await workExperienceApi.deleteWorkExperience(props.resumeId, experience.id)
      ElMessage.success('删除成功')
    } catch (error) {
      ElMessage.error('删除失败')
      return
    }
  }

  const index = workExperienceList.value.findIndex(item => item === experience)
  if (index > -1) {
    workExperienceList.value.splice(index, 1)
  }
}

// 保存工作经验
const handleSave = async () => {
  saving.value = true
  try {
    for (const experience of workExperienceList.value) {
      // 跳过空的工作经验
      if (!experience.company_name || !experience.position_name || !experience.job_responsibilities) {
        continue
      }

      if (experience.id) {
        // 更新
        await workExperienceApi.updateWorkExperience(props.resumeId, experience.id, experience)
      } else {
        // 创建
        const response = await workExperienceApi.createWorkExperience(props.resumeId, experience)
        const data = response.data || response
        experience.id = data.id
      }
    }

    ElMessage.success('工作经验保存成功')

    // 重新获取数据
    await fetchWorkExperienceList()

  } catch (error) {
    console.error('保存工作经验错误:', error)
    ElMessage.error('保存失败')
  } finally {
    saving.value = false
  }
}

// 生命周期
onMounted(() => {
  fetchWorkExperienceList()
})
</script>

<style lang="scss" scoped>
.work-experience-step {
  .step-header {
    margin-bottom: 32px;

    h3 {
      font-size: 24px;
      font-weight: 600;
      color: var(--text-color-primary);
      margin: 0 0 8px 0;
    }

    p {
      color: var(--text-color-secondary);
      margin: 0;
    }
  }

  .company-groups {
    .company-group {
      margin-bottom: 32px;
      border: 1px solid var(--border-color-light);
      border-radius: 8px;
      overflow: hidden;

      &:last-child {
        margin-bottom: 0;
      }

      .company-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 16px 20px;
        background: var(--fill-color-extra-light);
        border-bottom: 1px solid var(--border-color-light);

        .company-name {
          font-size: 16px;
          font-weight: 600;
          color: var(--text-color-primary);
          margin: 0;
        }
      }

      .positions-list {
        .position-item {
          padding: 24px;
          border-bottom: 1px solid var(--border-color-extra-light);

          &:last-child {
            border-bottom: none;
          }

          .experience-form {
            .form-actions {
              text-align: right;
              margin-top: 16px;
              padding-top: 16px;
              border-top: 1px solid var(--border-color-extra-light);
            }
          }
        }
      }
    }
  }

  .empty-state {
    padding: 60px 0;
    text-align: center;
  }

  .step-actions {
    margin-top: 32px;
    padding-top: 24px;
    border-top: 1px solid var(--border-color-extra-light);
    display: flex;
    gap: 12px;
  }
}

@media (max-width: 768px) {
  .work-experience-step {
    .company-groups {
      .company-group {
        .company-header {
          flex-direction: column;
          align-items: flex-start;
          gap: 12px;
        }

        .positions-list {
          .position-item {
            padding: 16px;

            .experience-form {
              .el-row {
                .el-col {
                  margin-bottom: 16px;
                }
              }
            }
          }
        }
      }
    }
  }
}
</style>
